package com.neasho.neashoadminv1.infrastructure.utils

import cn.hutool.http.useragent.UserAgent
import com.neasho.neashoadminv1.infrastructure.domain.sys.SysUser
import com.neasho.neashoadminv1.infrastructure.exception.BusinessCode

/**
 * 用户上下文
 */
class UserContext {
    companion object {
        val currentUser = ThreadLocal<SysUser>()
        val currentUserAgent = ThreadLocal<UserAgent>()
        /**
         * 设置用户
         */
        fun setUser(user: SysUser) {
            currentUser.set(user)
        }

        /**
         * 获取用户
         */
        fun getUser() : SysUser? = currentUser.get()

        /**
         * 用户名
         */
        fun username(): String? = currentUser.get()?.username

        fun getUserOrThrow() : SysUser = currentUser.get()?:throw BusinessCode.user_not_login.exception()

        /**
         * 清理用户
         */
        fun clear() {
            currentUser.remove()
        }

        fun setUserAgent(userAgent: UserAgent) {
            currentUserAgent.set(userAgent)
        }
        fun getUserAgent(): UserAgent? = currentUserAgent.get()
        fun clearUserAgent() {
            currentUserAgent.remove()
        }
    }
}